home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c++
- Path: netcom.com!marnold
- From: marnold@netcom.com (Matt Arnold)
- Subject: Re: Initializing each element in an array of classes
- Message-ID: <marnoldDo1KtL.C1A@netcom.com>
- Organization: NETCOM On-line Communication Services (408 261-4700 guest)
- References: <4hssvm$178_001@basmith1.iquest.net> <Do1A90.33L@presby.edu>
- Date: Sun, 10 Mar 1996 07:58:33 GMT
- Sender: marnold@netcom13.netcom.com
-
- jtbell@presby.edu (Jon Bell) writes:
-
- > Brian Smith <basmith@iquest.net> wrote:
- >>class Dot {
- >> int X;
- >> int Y;
- >> Dot(void);
- >> Dot(int InitX, int InitY, int InitSize = 1) // default for InitSize is 1
- >>};
-
- >>class Box {
- >> int i;
- >> int j;
- >> Dot DotArray[3];
- >> etc...
- >>}
-
- >>How can I create this array of Dots with the X and Y values of, for example,
- >>(1,1), (2,2), and (3,3)? The Borland Turbo C++ manual is of no help at all.
-
- By writing the ctor of Box like so...
-
- Box::Box():
- i(/* some value for i */),
- j(/* some value for j */)
- {
- DotArray[0] = Dot(1, 1);
- DotArray[1] = Dot(2, 2);
- DotArray[2] = Dot(3, 3);
- }
-
- There is no way to initialize an array member in the intializer list (as can
- be done for the int members i and j, as I showed). You will have to set the
- initial value of each array element in the ctor's body.
-
- An alternative to a built-in array of Dots is to the vector template class
- from the Standard Template Library (STL). vector has a constructor than can
- take another vector to intialize itself with (basically, it just copies the
- contents of the other vector). You could then intialize a vector member using
- some vector passed to box, or perhaps some default vector sitting around
- solely for the purpose of intializing the vector member of each instance of
- Box. Since vectors are single C++ objects, you can intialize them in the
- intializer list...
-
- #include "vector.h" // from STL
-
- class Box
- {
- vector<Dot> DotArray;
-
- public:
- Box(const vector<Dot>& InitialDots):
- DotArray(InitialDots)
- {
- }
- };
-
-
- Regards,
- -------------------------------------------------------------------------
- Matt Arnold | | ||| | |||| | | | || ||
- marnold@netcom.com | | ||| | |||| | | | || ||
- Boston, MA | 0 | ||| | |||| | | | || ||
- 617.389.7384 (h) 617.576.2760 (w) | | ||| | |||| | | | || ||
- C++, MIDI, Win32/95 developer | | ||| 4 3 1 0 8 3 || ||
- -------------------------------------------------------------------------
-